package com.liam.lotterysystem.common.Interceptor;

import io.jsonwebtoken.Claims;
import com.liam.lotterysystem.common.utils.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author: LiamLMK
 * @CreateTime: 2024-10-18
 * @Description: 拦截器
 * @Version: 1.0
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 预处理, 业务请求之前调用
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头
        String token = request.getHeader("user_token");
        log.info("获取token:{}", token);
        log.info("获取路径:{}", request.getRequestURI());
        // 令牌解析
        Claims claims = JWTUtil.parseJWT(token);
        /**
         * bug报告3: 导入JWTUtil的包的时候, 将jsonwebtoken的包错导成hutool, 导致方法名一样但内容不同, claims解析出来为null
         */
        if (claims == null) {
            log.error("解析JWT令牌失败");
            response.setStatus(401);
            return false;
        }
        log.info("解析JWT令牌成功, 放行");
        return true;
    }
}
